package com.logistics.socket.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.logistics.delivery.entity.model.DeliverySave;
import com.logistics.delivery.service.DeliveryService;
import com.logistics.heart.entity.model.HeartSave;
import com.logistics.heart.service.HeartService;
import com.logistics.socket.model.ResponseDeviceData;
import com.logistics.socket.model.ResponseSocketModel;
import com.logistics.utils.constants.Constants;
import com.logistics.utils.tool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 接受AGV调度平台返回数据服务
 */
@Service
public class ResponseSocketService {

    @Autowired
    private HeartService heartService;

    @Autowired
    private DeliveryService deliveryService;

    public static ConcurrentHashMap<String, Boolean> callBackMap = new ConcurrentHashMap<>();

    /**
     * 返回消息接口
     * @param msg
     */
    public void responseMessage(String msg){
        ResponseSocketModel response = StringUtils.stringToBena(msg, ResponseSocketModel.class);
        switch (response.getType()){
            // 发送任务
            case 1 : handlerTask(msg); break;
            // 返回心跳
            case 5 : handlerHeart(msg); break;
        }
    }

//    @Async("taskExecutor")
    public void handlerHeart(String msg){
        List<ResponseDeviceData> list = new ArrayList<>();
        JSONArray jsonArray = JSONObject.parseObject(msg).getJSONArray("data");
        if(StringUtils.isNotNull(jsonArray)){
            for (int i = 0; i < jsonArray.size(); i++) {
                list.add(JSONObject.parseObject(jsonArray.get(i).toString(), ResponseDeviceData.class));
            }
            heartService.merge(list.stream().map(HeartSave::build).collect(Collectors.toList()));
        }
    }

//    @Async("taskExecutor")
    public void handlerTask(String msg){
        System.out.println("原始json"+msg);
        ResponseSocketModel response = StringUtils.stringToBena(msg, ResponseSocketModel.class);
        DeliverySave save = new DeliverySave();
        save.setReqCode(response.getRescode());
        save.setAgv(response.getAgvinfo());
        save.setStatus(getStatus(response.getReqtype()));
        deliveryService.updateDeliveryByReqCode(save);
        callWriteHeartState(response.getAgvinfo());
    }

    /**
     * 获取状态码
     * @param type
     * @return
     */
    private String getStatus(Integer type){
        if(StringUtils.isNotNull(type)){
            if(type == 0 || type == 1 || type == 2){
                return Constants.DELIVERY_STATE_IN;
            }else if (type == 3){
                return Constants.DELIVERY_STATE_SUCCESS;
            }else if (type == 4){
                return Constants.DELIVERY_STATE_CANCEL;
            }else{
                // 如果失败回写任务状态 等待配送
                return Constants.DELIVERY_STATE_STANDBY;
            }
        }
        return Constants.DELIVERY_STATE_STANDBY;
    }

    /**
     * 回写状态
     * @return
     */
    private void callWriteHeartState(String deviceId){
        if(StringUtils.isNotNull(deviceId) &&
                StringUtils.isNotNull(callBackMap.get(deviceId)) && callBackMap.get(deviceId)){
            heartService.updateStateByIp(Constants.HANDLER_STATE_STANDBY, deviceId);
            callBackMap.remove(deviceId);
        }
    }
}
